<?php

namespace App\Models\Admin;

use App\Scopes\SaasScope;
use App\User;
use App\Models\DispatchOrder as Order;
use App\Models\SortingLogs;
use App\Models\Setting;
use Auth;
use Illuminate\Database\Eloquent\Model;

class DispatchOrderList extends Model
{

    protected $table = 'dispatch_order_list';

    protected $dateFormat = 'U';

    public $timestamps = true;

    protected $guarded = [];

    public function user()
    {
        return $this->hasOne(User::class,'id','sort_uid');
    }
    public function goods()
    {
        return $this->hasOne(Goods::class,'id','goods_id');
    }
    public function goodss()
    {
        return $this->hasOne(Goods::class,'id','goods_id')->with(['category','category_p']);
    }
    public function users()
    {
        return $this->hasOne(User::class,'id','sort_id')->select('name');
    }
    public function goodsSpu()
    {
        return $this->hasOne(GoodsSpu::class,'id','goods_spu_id');
    }

    public function member()
    {
        return $this->hasOne(User::class,'id','dispatch_user_id')->select('id','name')->withoutGlobalScopes();
    }

    public function companyName()
    {
        return $this->hasOne(Company::class,'id','company_uid')->select('id','company_name');
    }

    public function order()
    {
        return $this->hasOne(DispatchOrder::class,'id','oid');
    }
    public function address()
    {
        return $this->hasOne(Setting::class,'id','company_uid')->select('id','receive_man','receive_mobile','receive_address');
    }
//    public function storehouse_inventory()
//    {
//        return $this->hasOne(StorehouseInventory::class,'goods_spu_id','goods_spu_id')->select('id','num','price');
//    }

    public function getList($send_time,$send_time_id=0,$line_id=0,$category_id=0,$pid=0,$uids=[],$goods_ids=[],$is_purchase=false)
    {
        //订单ID集合
        $oids = DispatchOrder::whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status not in(0,4)")
            ->when($send_time_id,function ($query)use ($send_time_id){
                $query->where('send_time_id',$send_time_id);
            })->when($line_id,function ($query)use ($line_id){
                $query->where('line_id',$line_id);
            })->when(!empty($uids),function ($query)use ($uids){
                $query->whereIn('company_uid',$uids);
            })->pluck('id');
        $list = $this->with(['member','order','companyName'])->when(!empty($pid),function ($query)use ($pid){
            $query->where('pid',$pid);
        })->when(!empty($category_id),function ($query)use ($category_id){
            $query->where('category_id',$category_id);
        })->when(!empty($goods_ids),function ($query)use($goods_ids){
            $query->whereIn('goods_id',$goods_ids);
        })->when($is_purchase,function ($query){
            $query->where('is_purchase',0);
//        })->whereIn('oid',$oids)->orderBy('order_num','ASC')->get()->groupBy('goods_spu_id')->toArray();
        })->whereIn('oid',$oids)->orderBy('category_id','ASC')->orderBy('pid','ASC')->orderBy('order_num','ASC')->get()->groupBy('goods_spu_id')->toArray();
        //修改原有 订单汇总里面 按分类排序
        return $list;
    }

    public function getPlanList($send_time,$send_time_id=0,$line_id=0,$category_id=0,$pid=0,$uids=[],$goods_ids=[],$is_purchase=false,$order_time_at,$order_time_down)
    {
        //订单ID集合
        $oids = DispatchOrder::whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status = 1")
            ->when($order_time_at && $order_time_down,function ($query)use ($order_time_at,$order_time_down){
                $query->whereBetween('created_at',[strtotime($order_time_at),strtotime($order_time_down)]);
            })
            ->when($send_time_id,function ($query)use ($send_time_id){
                $query->where('send_time_id',$send_time_id);
            })->when($line_id,function ($query)use ($line_id){
                $query->where('line_id',$line_id);
            })->when(!empty($uids),function ($query)use ($uids){
                $query->whereIn('company_uid',$uids);
            })->pluck('id');
        $list = $this->with(['member','order','companyName'])->when(!empty($pid),function ($query)use ($pid){
            $query->where('pid',$pid);
        })->when(!empty($category_id),function ($query)use ($category_id){
            $query->where('category_id',$category_id);
        })->when(!empty($goods_ids),function ($query)use($goods_ids){
            $query->whereIn('goods_id',$goods_ids);
        })->when($is_purchase,function ($query){
            $query->where('is_purchase',0);
        })->whereIn('oid',$oids)->orderBy('category_id','ASC')->orderBy('pid','ASC')->orderBy('order_num','ASC')->get()->groupBy('goods_spu_id')->toArray();
        return $list;
    }

    public function collect($send_time,$data = [])
    {
        $category_id = $data['category_id'];
        $pid = $data['pid'];
        $send_time_id = $data['send_time_id'];
        $line_id = $data['line_id'];
        $uids = $goods_ids = [];
        if ($group_id = $data['group_id']){
            $uids = MemberInfo::where('group_id',$group_id)->pluck('user_id');
        }
        if ($name = $data['name']){
            $goods_ids = Goods::where('name','like',"%$name%")->pluck('id');
        }
        $list = $this->getList($send_time,$send_time_id,$line_id,$category_id,$pid,$uids,$goods_ids);
        $data = [];
        foreach($list as $k => $v){
            $spuInfo = GoodsSpu::with(['spuName','spuUnit','goods'])->find($k);
            $order_num = $order_money = $send_num = $send_money = $return_num = $return_money = 0;
            $order_list = [];
            foreach($v as $key => $val){
                $order_num += $val['order_num'];
                $order_money += bcmul($val['order_num'],$val['order_price'],2);
                $send_num += $val['sort_num'];
                $send_money += bcmul($val['sort_num'],$val['sort_price'],2);
                $return_num += $val['return_num'];
                $return_money += bcmul($val['return_num'],$val['sort_price'],2);

                $order_list[] = [
                    'order_sn' => $val['order']['order_sn'],
                    'nickname' => $val['company_name']['company_name'],
                    'order_num' => $val['order_num'],
                    'order_price' => $val['order_price'],
                    'order_money' => bcmul($val['order_num'],$val['order_price'],2),
                    'sort_num' => $val['sort_num'],
                    'sort_price' => $val['sort_price'],
                    'send_money' => bcmul($val['sort_num'],$val['sort_price'],2),
                    'really_money' => bcmul($val['sort_num'],$val['sort_price'],2) - bcmul($val['return_num'],$val['sort_price'],2),
                    'remark' => $val['remark']
                ];
            }
            $data[] = [
                'name' => $spuInfo->goods->name.'【'.$spuInfo->spuName->title.'】',
                'unit' => $spuInfo->spuUnit->title,
                'order_num' => $order_num,
                'order_money' => $order_money,
                'send_num' => $send_num,
                'send_money' => $send_money,
                'return_num' => $return_num,
                'return_money' => $return_money,
                'really_money' => $send_money - $return_money,
                'order_list' => $order_list,
            ];
        }
        return $data;
    }
    //增加
    public function addList($id,$num,$sort_uid){
        $arr=[];
        if($num==0){
            $this->quhuo($id);
        }
        if($num){
            $arr['sort_num']=$num;
        }
        $arr['sort_uid']=$sort_uid;
        $arr['sort_time']=time();
        $arr['status']=1;
        $result=$this->where('id',$id)->update($arr);
        if($result) {
            $this->kucun($id);
            $this->order_sort_start($id);
            $this->upsend_money($id);
            return  $this->logs_list($id);
        }
    }
    //一键分拣
    public function on_sort($id){
        $data=$this->where('id',$id)->select('status','order_num')->first()->toArray();
        $order_num=$data['order_num'];
        if($data['status']==0 ){
            $this->kucun($id);
            $this->where('id',$id)->update(['status'=>1,'sort_time'=>time(),'sort_num'=>$order_num,'sort_uid'=>Auth::id()]);
            $this->upsend_money($id);
            $this->order_sort_start($id);
            return $this->logs_list($id);
        }

    }
    //累加
    public function accumulationlist($id,$num,$sort_uid){
        $string=$this->where('id',$id)->select('cumulative_record')->first();
        if($string->cumulative_record==null){
            $str=$num;
        }else{
            $str=$string->cumulative_record.','.$num;
        }
        $this->kucun($id);
        $result=$this->where('id',$id)->update(['sort_uid'=>$sort_uid,'sort_time'=>time(),'status'=>1,'cumulative_record'=>$str]);
        $result1=$this->where('id',$id)->increment('sort_num',$num);
        $this->upsend_money($id);
        $this->order_sort_start($id);
        if($result && $result1){
           return $this->logs_list($id);
        }

    }
    //撤销
    public function revokeList($id){
        $arr=[
            'sort_num'=>0,
            'status'=>0,
            'mfg'=>null,
            'sort_time'=>0,
            'sort_uid'=>0,
            'cumulative_record'=>null,
            'out_status'=>0,
            'inventory_price'=>0
        ];
        $result=$this->where('id',$id)->update($arr);
        $this->upsend_money($id);
        $this->order_sort_start($id);
        $this->logs_list($id);
        return $result;
    }
//    //生成分拣记录表
//    public function sort_log($id){
//        $data=$this->where('id',$id)->select('id','company_uid','goods_id','goods_spu_id','sort_uid','order_num','sort_time','company_id','sort_num')->first();
//        $arr=[
//            'order_list_id'=>$data->id,
//            'goods_id'=>$data->goods_id,
//            'goods_spu_id'=>$data->goods_spu_id,
//            'sor_id'=>$data->sort_uid,
//            'num'=>$data->order_num,
//            'company_uid'=>$data->company_uid,
//            'sor_num'=>$data->sort_num,
//            'sor_time'=>$data->sort_time,
//            'company_id'=>$data->company_id
//        ];
//        $result2=SortingLogs::insert($arr);
//        if($result2){
//            return true;
//        }
//    }
    //缺货
    public function stockList($id){
        $this->quhuo($id);
    }
    function quhuo($id){
        $arr=[
            'sort_num'=>0,
            'status'=>1,
            'out_status'=>1
        ];
        $result=$this->where('id',$id)->update($arr);
        $this->upsend_money($id);
        $this->order_sort_start($id);
        $this->logs_list($id);
        return $result;
    }
    //加库存
    public function kucun($id){
        $cost_entry_rule=config('pin_setting.cost_entry_rule');
        if($cost_entry_rule){
            return true;
        }
        $data=$this->where('id',$id)->select('goods_spu_id')->first()->toArray();
        $data=StorehouseInventory::where('goods_spu_id',$data['goods_spu_id'])->select('goods_spu_id','price','num')->first();
        if($data){
            $inventory_price=$data->price;
        }else{
            $inventory_price=0;
        }
        $result=$this->where('id',$id)->update(['inventory_price'=>$inventory_price]);
        return $result;
    }
    /**
     *  分拣记录
     * @param
     */
    function logs_list($id){
        $data=$this->find($id);
        $arr=['order_list_id'=>$id,'goods_id'=>$data->goods_id,'goods_spu_id'=>$data->goods_spu_id,'sor_id'=>$data->sort_uid,
            'num'=>$data->order_num,'sor_num'=>$data->sort_num,'sor_time'=>$data->sort_time,'company_id'=>$data->company_id,
            'company_uid'=>$data->company_uid,'created_at'=>time(),'updated_at'=>time()];
        $result2=SortingLogs::insert($arr);
        if($result2){
            return true;
        }
    }
    //查订单状态下面商品分拣状态 0未分拣 1部分分拣 2已分拣
    function order_sort_start($orderListId){
        $Order=new Order;
        $ordr_list=$this->where('id',$orderListId)->select('oid')->first();
        $order=$Order->where('id',$ordr_list['oid'])->select('id')->first()->toArray();
        $order=$this->where('oid',$order['id'])->select('status')->get()->toArray();
        $arr_user=[];

        $order_list_status=0;
        foreach ($order as $v1){
            $arr_user[]=$v1['status'];
        }
        if(!in_array(1,$arr_user)){ //未分拣
            $order_list_status=0;
        }
        if(in_array(0,$arr_user) && in_array(1,$arr_user)){//部分分拣
            $order_list_status=1;
        }
        if(!in_array(0,$arr_user)){//已分拣
            $order_list_status=2;
        }
        $info = $Order->findOrFail($ordr_list['oid']);
        $perInfo = $info->getOriginal();
        $info->order_list_status = $order_list_status;
        $info->save();
        $nextInfo = $info->getChanges();
        if (method_exists($Order,'addLog')){

//            if (!empty($nextInfo)){
//                $Order->addLog($perInfo,$nextInfo,6,'order_sort_start',2);
//            }
        }

    }
    function upsend_money($id){
        $Order=new Order;
        $order_id=$this->where('id',$id)->select('oid')->first();
        $sort_money = $this->where('oid',$order_id->oid)->selectRaw("id,oid,sort_num,sort_price,(sort_price * sort_num) as sort_money")->get()->sum('sort_money');
        $Order->where('id',$order_id->oid)->update(['send_money'=>$sort_money]);
    }
    /*+++++++++++++++++++++++++++++分拣监控管理++++++++++++++++++++++++++++++++*/
    public function user_sort_list($request){
        $Order=new Order;
        $id =$Order->seach($request);
        $data=$this->model->whereIn('company_uid',$id)->get();
        return $data;
    }
}
